/* @jsxImportSource vue */
<script lang="tsx" setup>
import { computed, onMounted, reactive, ref, UnwrapRef } from "vue";
import {
  DeleteOutlined,
  EditOutlined,
  SearchOutlined,
  EyeOutlined,
  FilterOutlined,
  ReloadOutlined,
  IdcardOutlined
} from "@ant-design/icons-vue";
import {
  delSpaceUsingPost,
  listSpaceVoByPageUsingPost
} from "@/api/SpaceController";
import { message, Modal } from "ant-design-vue";
import dayjs from "dayjs";
import {
  SPACE_LEVEL_MAP,
  SPACE_LEVEL_OPTIONS,
} from "../../constants/space";
import {useRouter} from "vue-router";
import UserVO = API.UserVO;

interface FormState {
  layout: 'horizontal' | 'vertical' | 'inline';
}

interface SpaceVO extends API.SpaceVO {
  userAvatar?: string;
  formattedSize?: string;
  usagePercent?: number;
  user?:UserVO
}


// 表格数据相关
const dataList = ref<SpaceVO[]>([]);
const total = ref<number>(0);
const loading = ref(false);
const showDetail = ref(false);
const currentSpace = ref<SpaceVO>();

// 搜索条件
const searchParams = reactive<API.SpaceQueryRequest>({
  pageSize: 10,
  current: 1,
  sortOrder: 'ascend',
  sortField: 'createTime',
  spaceName: undefined,
  spaceLevel: undefined,
  status: undefined,
  userName: undefined
});

interface FormState {
  layout: 'horizontal' | 'vertical' | 'inline';
}

interface SpaceVO extends API.SpaceVO {
  userAvatar?: string;
  formattedSize?: string;
  usagePercent?: number;
  user?: UserVO
}

const formState: UnwrapRef<FormState> = reactive({
  layout: 'horizontal',
});


// 表格列配置
const columns = [
  {
    title: '所属用户',
    dataIndex: 'user',
    width: 180,
  },
  {
    title: '存储使用',
    key: 'storage',
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 100,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 160
  },
  {
    title: '操作',
    key: 'action',
    fixed: 'right',
    width: 150,
  }
];

const actions = [
  { icon: EyeOutlined, text: '详情', action: 'view' },
  { icon: EditOutlined, text: '编辑', action: 'edit' },
  { icon: DeleteOutlined, text: '删除', action: 'delete', danger: true }
];

// 字节格式化
const formatSize = (bytes: number) => {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 获取数据
const getData = async () => {
  try {
    loading.value = true;
    const res = await listSpaceVoByPageUsingPost(searchParams);
    if (res.data.code === 0 && res.data.data) {
      dataList.value = (res.data.data.records ?? []).map(space => ({
        ...space,
        // 添加用户信息处理
        userName: space.user?.userName || '未知用户',
        userId: space.user?.id || '',
        formattedSize: formatSize(space.totalSize || 0),
        usagePercent: Math.min(
            ((space.totalCount || 0) / (space.maxCount || 1)) * 100,
            100
        ).toFixed(2)
      }));
      total.value = res.data.data.total ?? 0;
    } else {
      message.error('数据获取失败：' + res.data.message);
    }
  } catch (e) {
    message.error('请求异常');
  } finally {
    loading.value = false;
  }
};
const router = useRouter()
// 重置搜索条件
const resetSearch = () => {
  Object.assign(searchParams, {
    current: 1,
    spaceName: undefined,
    spaceLevel: undefined,
    status: undefined,
    userName: undefined
  });
  getData();
};

// 分页配置
const pagination = computed(() => ({
  current: searchParams.current,
  pageSize: searchParams.pageSize,
  total: total.value,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  pageSizeOptions: ['10', '20', '50', '100']
}));

// 表格变化处理
const doTableChange = (page: any) => {
  searchParams.current = page.current;
  searchParams.pageSize = page.pageSize;
  getData();
};

// 操作处理
const handleAction = (action: string, record: SpaceVO) => {
  switch (action) {
    case 'view':
      currentSpace.value = record;
      showDetail.value = true;
      break;
    case 'edit':
      // 编辑逻辑
        router.push(`/add_space?id=${record.id}`)
      break;
    case 'delete':
      Modal.confirm({
        title: '确认删除空间？',
        content: `将永久删除空间 "${record.spaceName}" 及其所有文件`,
        onOk: async () => {
          await delSpaceUsingPost({ id: record.id });
          message.success('删除成功');
          await getData();
        }
      });
      break;
  }
};

onMounted(getData);
</script>

<template>
  <div class="space-management-container">
    <!-- 搜索区域 -->
    <div class="search-card">
      <a-form @finish="getData" class="search-form">
        <a-row :gutter="[16, 16]">
          <a-col :xs="24" :sm="12" :md="8">
            <a-input
                v-model:value="searchParams.spaceName"
                placeholder="空间名称"
                allow-clear
            >
              <template #prefix>
                <SearchOutlined />
              </template>
            </a-input>
          </a-col>

          <!-- 修改搜索项为搜索用户ID -->
          <a-col :xs="24" :sm="12" :md="8">
            <a-input
                v-model:value="searchParams.userName"
                placeholder="用户ID/昵称"
                allow-clear
            >
              <template #prefix>
                <IdcardOutlined />
              </template>
            </a-input>
          </a-col>

          <a-col :xs="24" :sm="12" :md="8">
            <a-select
                v-model:value="searchParams.spaceLevel"
                placeholder="空间级别"
                :options="SPACE_LEVEL_OPTIONS"
                allow-clear
            />
          </a-col>

          <a-col :xs="24" :sm="24" :md="24" class="action-col">
            <a-button type="primary" html-type="submit" @click="getData">
              <template #icon><FilterOutlined /></template>
              筛选
            </a-button>
            <a-button @click="resetSearch" style="margin-left: 12px">
              <template #icon><ReloadOutlined /></template>
              重置
            </a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 数据表格 -->
    <div class="data-table-card">
      <a-table
          :columns="columns"
          :data-source="dataList"
          :pagination="pagination"
          :loading="loading"
          :scroll="{ x: 1200 }"
          @change="doTableChange"
          bordered
      >
        <!-- 所属用户列 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'user'">
            <a-table-cell>
              <div class="user-cell">
                <div class="user-name">{{ record.user?.userName || '未知用户' }}</div>
                <div class="user-id">ID: {{ record.user?.id || '未知ID' }}</div>
              </div>
            </a-table-cell>
          </template>

          <!-- 存储使用列 -->
          <template v-else-if="column.key === 'storage'">
            <a-table-cell>
              <div class="storage-progress">
                <div
                    class="progress-bar"
                    :style="{ width: `${record.usagePercent}%` }"
                ></div>
                <div class="storage-info">
                  <span>{{ record.formattedSize }}</span>
                  <span>{{ record.totalCount }}个文件</span>
                </div>
              </div>
            </a-table-cell>
          </template>

          <!-- 状态列 -->
          <template v-else-if="column.dataIndex === 'status'">
            <a-table-cell>
              <Tag :color="record.status === 0 ? 'green' : 'red'">
                {{ record.status === 0 ? '正常' : '停用' }}
              </Tag>
            </a-table-cell>
          </template>

          <!-- 创建时间列 -->
          <template v-else-if="column.dataIndex === 'createTime'">
            <a-table-cell>
              {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm') }}
            </a-table-cell>
          </template>

          <!-- 操作列 -->
          <template v-else-if="column.key === 'action'">
            <a-table-cell>
              <div class="action-buttons">
                <a-tooltip v-for="btn in actions" :key="btn.action">
                  <a-button
                      :type="btn.danger ? 'dashed' : 'text'"
                      :danger="btn.danger"
                      @click="handleAction(btn.action, record)"
                  >
                    <component :is="btn.icon" />
                    {{ btn.text }}
                  </a-button>
                </a-tooltip>
              </div>
            </a-table-cell>
          </template>
        </template>

        <template #empty>
          <div class="empty-state">
            <img src="@/assets/empty-space.svg" alt="空状态" />
            <p>暂无空间数据</p>
          </div>
        </template>
      </a-table>
    </div>

    <!-- 空间详情抽屉 -->
    <a-drawer
        v-model:visible="showDetail"
        title="空间详情"
        width="40%"
    >
      <div v-if="currentSpace" class="space-detail">
        <a-descriptions :column="1" bordered>
          <a-descriptions-item label="空间名称">
            {{ currentSpace.spaceName }}
          </a-descriptions-item>
          <a-descriptions-item label="所属用户">
            <div class="user-info">
              <a-avatar :src="currentSpace.userAvatar" />
              <span>{{ currentSpace.userName }}</span>
            </div>
          </a-descriptions-item>
          <a-descriptions-item label="存储使用">
            <div class="storage-progress">
              <div
                  class="progress-bar"
                  :style="{ width: currentSpace.usagePercent + '%' }"
              ></div>
              <div class="storage-info">
                <span>{{ currentSpace.formattedSize }}</span>
                <span>{{ currentSpace.totalCount }}个文件</span>
              </div>
            </div>
          </a-descriptions-item>
          <a-descriptions-item label="创建时间">
            {{ dayjs(currentSpace.createTime).format('YYYY-MM-DD HH:mm') }}
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-drawer>
  </div>
</template>

<style scoped lang="less">
@import "@/assets/variable.less";

.space-management-container {
  padding: 24px;
  background: @background-color-light;
}

.search-card {
  background: white;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: @box-shadow-base;

  .action-col {
    display: flex;
    justify-content: flex-end;
  }
}

.data-table-card {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: @box-shadow-base;
}

.storage-progress {
  position: relative;
  height: 32px;
  background: #f5f5f5;
  border-radius: 4px;
  overflow: hidden;

  .progress-bar {
    position: absolute;
    height: 100%;
    background: @primary-color;
    opacity: 0.3;
    transition: width 0.3s;
  }

  .storage-info {
    position: relative;
    display: flex;
    justify-content: space-between;
    padding: 0 12px;
    line-height: 32px;
    font-size: 12px;
  }
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;

  span {
    font-weight: 500;
  }
}

.action-buttons {
  display: flex;
  gap: 8px;

  button {
    padding: 0 8px;
  }
}
// 添加用户信息样式
.user-cell {
  line-height: 1.4;

  .user-name {
    font-weight: 500;
    margin-bottom: 2px;
  }

  .user-id {
    font-size: 12px;
    color: @text-color-secondary;
    font-family: monospace;
  }
}

// 调整列宽
.ant-table-thead {
  .ant-table-cell[data-column="所属用户"] {
    min-width: 180px;
  }
}

// 详情页用户信息样式
.user-info {
  display: flex;
  align-items: center;
  gap: 8px;

  span {
    display: flex;
    flex-direction: column;

    &::after {
      content: attr(data-userid);
      font-size: 12px;
      color: @text-color-secondary;
      margin-top: 2px;
    }
  }
}
.empty-state {
  text-align: center;
  padding: 40px 0;

  img {
    width: 200px;
    margin-bottom: 16px;
  }

  p {
    color: @text-color-secondary;
  }
}

.space-detail {
  :deep(.ant-descriptions-item-label) {
    font-weight: 500;
    width: 120px;
  }
}

@media (max-width: 768px) {
  .search-card {
    padding: 16px;
  }

  .data-table-card {
    padding: 16px;
  }

  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }
}
.user-cell {
  line-height: 1.4;
  .user-name {
    font-weight: 500;
  }
  .user-id {
    font-size: 12px;
    color: #666;
  }
}

.storage-progress {
  position: relative;
  height: 30px;
  background: #f5f5f5;
  border-radius: 4px;
  overflow: hidden;

  .progress-bar {
    position: absolute;
    height: 100%;
    background: #1890ff;
    transition: width 0.3s;
  }

  .storage-info {
    position: relative;
    padding: 0 8px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 100%;
    font-size: 12px;
    color: #fff;
  }
}

.action-buttons {
  display: flex;
  gap: 8px;

  :deep(.ant-btn) {
    display: flex;
    align-items: center;
    gap: 4px;
  }
}
</style>
